/*
 * 列表组件，最终转换出html5
 * <div id="passenger-list">
 *  <div class="contentScroller">
 *  </div>
 * </div>
 *
 */
define(['jquery', 'underscore', '../components/loader', '../components/cache', '../components/store', 'gmu', 'backbone'
        // , 'components/reloginAjax'
        , 'i18n!../components/nls/list', '../../com.52zzb.common/config'
    ],



    function($, _, Loader, Cache, Store, gmu, Backbone, Locale, Config
        // ,Relogin
    ) {

        var List = Backbone.View.extend({

            tagName: 'div',
            //渲染组件时，此组件所在上下文，可能未attach到document，所以一些元素查找，需要在上下文内查找，例如itemTemplate
            elContext: document,

            events: {
                // "": "reload"
                "click .cube-list-item": "onItemSelect",

            },

            requestParams: {},
            isLoadNext: false,

            config: {
                /*提取到父类*/
                observers: [],
                /*自有*/
                width: '100%',
                height: '500',
                autoLoad: "true",
                pageParam: 'page',
                pageSizeParam: 'pageSize',
                topOffset: 40,
                page: 1,
                pageSize: 10,
                pullDownEnable: 'false',
                isPullDownRefresh: 'true',
                pagingEnable: true,
                iScroll: 'true',
                method: 'GET',
                filterStr: null,
                offLine: "false", //离线
                offLinePaging: true,
                isNeedUpdateCache: true, //离线数据是否需要更新
                momentum: true,
                pagecount: 1,
                picserver: Config.picserver,
                image100jpg: Config.image100jpg,
                image120jpg: Config.image120jpg,
                image80jpg: Config.imageView80,
                imagew300jpg: Config.imagew300jpg,
                imagew200jpg: Config.imagew200jpg,
                imagew600jpg: Config.imagew600jpg,
                image108jpg: Config.image108jpg

            },

            request: null,
            enableRequest: true,

            initialize: function() {
                var me = this;
                //获取传入参数
                if (arguments && arguments.length > 0) {
                    var config = arguments[0];
                    //这样取得的config将会被几个list共享
                    // this.config = _.extend(this.config, object);

                    var key;
                    for (key in config) {
                        if (key in this) this[key] = config[key];
                    }

                    var obj = {};
                    for (var configKey in this.config) {
                        obj[configKey] = this.config[configKey];
                    }
                    for (var argkey in config) {
                        obj[argkey] = config[argkey];
                    }
                    this.config = obj;
                }

                //iScroll
                if (this.config.iScroll != 'false') {
                    var isAutoTrigger = true;
                    var list_iScroll = new iScroll(this.el, {
                        onBeforeScrollStart: function(e) {
                            var target = e.target;
                            while (target.nodeType != 1) target = target.parentNode;
                            if (target.tagName != 'TEXTAREA' && target.tagName != 'INPUT' && target.tagName != 'SELECT') e.preventDefault();
                        },
                        topOffset: config.topOffset,
                        useTransition: true,
                        // bounceLock: true,
                        // momentum:false,
                        onRefresh: function() {
                            pullUpEl = me.$('#pullUp')[0];
                            if (pullUpEl != null) {
                                pullUpOffset = pullUpEl.offsetHeight;
                                if (pullUpEl.className.match('loading')) {
                                    pullUpEl.className = '';
                                    pullUpEl.querySelector('.pullUpLabel').innerHTML = Locale.pullup_load_more;
                                }
                            }
                        },
                        onScrollMove: function() {
                            isAutoTrigger = false;
                            Cache.put("onScrollMove", "true");
                            pullUpEl = me.$('#pullUp')[0];
                            if (pullUpEl != null) {
                                // console.log('Release = *******************'+this.maxScrollY);
                                pullUpOffset = pullUpEl.offsetHeight;

                                var pullUpReloadHeight = 5;

                                if (this.y < (this.maxScrollY) && !pullUpEl.className.match('flip')) {
                                    pullUpEl.className = 'flip';
                                    pullUpEl.querySelector(me.config.pageId + ' .pullUpLabel').innerHTML = Locale.release_to_load;
                                    //this.maxScrollY = this.maxScrollY;
                                } else if (this.y > (this.maxScrollY) && pullUpEl.className.match('flip')) {
                                    pullUpEl.className = '';
                                    pullUpEl.querySelector(me.config.pageId + ' .pullUpLabel').innerHTML = Locale.pullup_load_more;
                                    //this.maxScrollY = pullUpOffset;
                                }
                                // if (this.y < (this.maxScrollY - pullUpReloadHeight) && !pullUpEl.className.match('flip')) {
                                //     pullUpEl.className = 'flip';
                                //     pullUpEl.querySelector('.pullUpLabel').innerHTML = Locale.release_to_load;
                                //     //this.maxScrollY = this.maxScrollY;
                                // } else if (this.y > (this.maxScrollY + pullUpReloadHeight) && pullUpEl.className.match('flip')) {
                                //     pullUpEl.className = '';
                                //     pullUpEl.querySelector('.pullUpLabel').innerHTML = Locale.pullup_load_more;
                                //     //this.maxScrollY = pullUpOffset;
                                // }


                            }
                            var pullDownRefreshHeight = 40;
                            pullDownRefreshEl = me.$(me.config.pageId + ' #PullDownRefresh')[0];

                            if (pullDownRefreshEl) {
                                if ((this.y > pullDownRefreshHeight) && (this.options.topOffset > 0)) {

                                    this.options.topOffset = 0;
                                    $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshIcon').attr({
                                        'class': 'pullDownIn'
                                    });
                                    //$(pullDownRefreshEl).find('#pullDownRefreshLable').text(Locale.release_to_update);
                                    $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshLable').html('<div class="spinner"><span>松手更新</span><div class="bounce2"></div></div>');
                                    $(me.$(me.config.pageId + ' #pullDownRefreshIconWarp')[0]).addClass('pullDownFlip180');



                                } else if ((this.y < pullDownRefreshHeight) && (this.options.topOffset == 0)) {
                                    this.options.topOffset = parseInt($(pullDownRefreshEl).css('height'));
                                    $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshIcon').removeClass('pullDownOut').addClass('pullDownIn');
                                    //$(pullDownRefreshEl).find('#pullDownRefreshLable').text(Locale.pulldown_to_refresh);
                                    $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshLable').html('<div class="spinner"><span>下拉刷新</span></div>');
                                    Cache.put("onScrollMove", "false");
                                    $(me.$(me.config.pageId + ' #pullDownRefreshIconWarp')[0]).removeClass('pullDownFlip180');

                                } else if (this.y > 0) {
                                    Cache.put("onScrollMove", "false");

                                }


                            }
                        },
                        onBeforeScrollEnd: function() {
                            pullDownRefreshEl = me.$(me.config.pageId + ' #PullDownRefresh')[0];

                            if ((pullDownRefreshEl != null) && (this.options.topOffset == 0)) {
                                $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshIcon')
                                    .removeClass('pullDownIn')
                                    .addClass('pullDownOut');
                                // $(pullDownRefreshEl).find('#pullDownRefreshLable').text(Locale.data_updating);
                                $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshLable').html('<div class="spinner"><span style="width:50px;height:20px;">加载中</span><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
                                this.refresh();
                            }
                            //
                        },
                        reloadAction: null, //do something after reload
                        onScrollEnd: function() {

                            pullUpEl = me.$(me.config.pageId + ' #pullUp')[0];

                            var CACHE_ID = 'cube-list-' + me.config['id'];
                            if (!isAutoTrigger) {
                                Store.saveObject(CACHE_ID + "-scrollY", me.iScroll.y);
                                isAutoTrigger = true;
                            }

                            if (pullUpEl != null) {
                                pullUpOffset = pullUpEl.offsetHeight;

                                if (pullUpEl.className.match('flip')) {
                                    pullUpEl.className = 'loading';
                                    pullUpEl.querySelector(me.config.pageId + ' .pullUpLabel').innerHTML = Locale.data_loading;
                                    me.config.page = me.config.page + 1;
                                    me.config.pagecount = me.config.pagecount + 1;

                                    if (me.reloadAction) {
                                        me.loadNextPage(me.reloadAction);
                                    } else if (me.config.offLine == "true" || me.config.offLine == true) {
                                        var CACHE_ID = 'cube-list-' + me.config['id'];
                                        var arr = Cache.get(CACHE_ID);
                                        var ps = parseInt(me.config.pageSize); //pageSize
                                        var p = parseInt(me.config.page); //page
                                        var tempArr = me._subJSONArray(arr, (p - 1) * ps, (p - 1) * ps + ps);
                                        me.loadListByJSONArray(tempArr);
                                    } else {
                                        me.loadNextPage();
                                    }


                                    Cache.put("onScrollMove", "false");
                                }
                            }


                            // me.resetPullDownPos(me.iScroll.scrollY);
                            me.resetPullDownPos();
                            pullDownRefreshEl = me.$(me.config.pageId + ' #PullDownRefresh')[0];
                            if ((pullDownRefreshEl != null) && (this.options.topOffset == 0)) {
                                var that = this;

                                $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshIcon').attr({
                                    'class': 'pullDownOut'
                                });

                                me.resetPullDownPos();
                                // me.resetPullDownPos(me.iScroll.scrollY);
                                setTimeout(function() {
                                    me.reload(function() {

                                        // console.log(11111);

                                        Cache.put("onScrollMove", "false");

                                        // $(pullDownRefreshEl).find('#pullDownRefreshLable').text(Locale.pulldown_to_refresh);
                                        // $(pullDownRefreshEl).find('#pullDownRefreshLable').html('<div class="spinner"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
                                        $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshLable').html('<div class="spinner"><span>刷新成功</span></div>');
                                        setTimeout(function() {
                                            that.options.topOffset = parseInt($(pullDownRefreshEl).css('height'));

                                            $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshIcon').attr({
                                                'class': 'pullDownIn'
                                            });

                                            $(me.$(me.config.pageId + ' #pullDownRefreshIconWarp')[0]).removeClass('pullDownFlip180');

                                            that.refresh();
                                        }, 500)


                                        setTimeout(function() {
                                            $(pullDownRefreshEl).find(me.config.pageId + ' #pullDownRefreshLable').html('<div class="spinner"><span>下拉刷新</span><div class="bounce1"></div></div>');
                                        }, 1000)

                                    });

                                }, 800)

                            }


                            var y = this.y;
                            var _winHeight = $(window).height();
                            $('.test-lazyload').each(function() {
                                var $self = $(this);
                                if ($self.attr('data-original')) {
                                    var _offsetTop = $self.offset().top;
                                    //console.log(_offsetTop);
                                    if (_offsetTop <= _winHeight + 100 && _offsetTop > -100) {
                                        $self.attr('src', $self.attr('data-original'));
                                        // $self.removeAttr('data-original');
                                        // if (me.config['iRefreshFag'] == 0) {
                                        //     me.config['iRefreshFag'] = 1;
                                        // }
                                    } else {
                                        $self.attr('src', '../com.52zzb.common/images/bg_load.png');
                                    }
                                }
                            });
                        }

                    });

                    this.iScroll = list_iScroll;
                    // refresh_iscroll = list_iScroll;
                    var me = this;
                    setTimeout(function() {
                        me.config.listSizeFix({
                            'iScroll': me.iScroll
                        });

                    }, 300);
                }

                if (this.config.autoLoad == 'true') this.reload();
            },


            home_refresh: function() { //调用在834行附近
                var me = this;
                this.iScroll.scrollTo(0, 0, 100, false);
                // this.iScroll.refresh();
                // $('#home_refresh').show();

                setTimeout(function() {
                    me.reload(function() {
                        // setTimeout(function() {
                        //     $('.bounce1').hide();
                        //     $('.bounce2').hide();
                        //     $('.bounce3').hide();
                        //     $('#home_refresh_span').text('刷新成功');
                        // }, 800)
                        // setTimeout(function() {
                        //     $('#home_refresh').hide();
                        //     $('#home_refresh_span').text('加载中');
                        //     $('.bounce1').show();
                        //     $('.bounce2').show();
                        //     $('.bounce3').show();
                        // }, 1600);
                    });
                }, 100)



            },

            onItemSelect: function(e) {
                var me = this;
                if (Cache.get("onScrollMove") == "true") {
                    Cache.put("onScrollMove", "false");
                    return;
                }


                var target = e.currentTarget;
                $(me.config.pageId + ' .cube-list-item').removeClass('pieceListSelect');
                $(target).addClass('pieceListSelect');
                var data = null;

                var index = target.getAttribute('index');
                var CACHE_ID = 'cube-list-' + this.config['id'];
                if (Cache.get(CACHE_ID)) {
                    var olddata = Cache.get(CACHE_ID);
                    data = olddata[index];

                }
                // var nodeName = e.toElement.nodeName;
                var nodeName = e.toElement != null ? e.toElement.nodeName : e.target.nodeName;
                if (this.shouldPreventListEvent(nodeName)) {
                    this.trigger("List:select", this, data, index, e);
                    //list, record(include event)
                    this.trigger("select", this, {
                        data: data,
                        index: index,
                        event: e
                    });
                }
            },

            render: function() {
                this.reload();
                return this;
            },

            reload: function(callback) {

                this.cleanStoreListData();
                if (this.config.pagecount > 1 && window.location.href.indexOf("#com.52zzb.main/example") <= 0) {

                } else {
                    Store.saveObject('reloadgogo', false);
                    this.config.page = 1;
                    this.loadNextPage(callback);
                }

                // Store.saveObject('reloadgogo', false);
                // this.config.page = 1;
                // this.loadNextPage(callback);

            },

            setRequestParams: function(params, callback, isAutoload) {
                // this.requestParams = params;
                this.requestParams = _.extend(this.requestParams, params); //comment by lee 2013.08.28
                if (isAutoload === undefined || isAutoload === null || isAutoload === true) {
                    this.reload(callback);
                    // this.callback = callback;
                }
            },

            filterChildren: function(keyWord) {
                var contentScroller = this.$(me.config.pageId + " .contentScroller");
                // if (this.iScroll) this.iScroll.scrollTo(0, 0);
                if (keyWord) {
                    contentScroller.find(me.config.pageId + " li[filter-keyword]").hide();
                    this.$('#' + this.config['id'] + ' li[filter-keyword*="' + keyWord.toLowerCase() + '"]').show();
                } else {
                    contentScroller.find(me.config.pageId + " li[filter-keyword]").show();
                }
                if (this.config.iScroll != 'false') this.iScroll.refresh();
            },
            refreshIscroll: function() {
                if (this.config.iScroll != 'false') this.iScroll.refresh();
            },

            shouldPreventListEvent: function(nodeName) {
                if (nodeName != 'TEXTAREA' && nodeName != 'INPUT' && nodeName != 'SELECT') return true;
                else return false;
            },

            _subJSONArray: function(array, startIndex, endIndex) {
                var tempArray = new Array();

                if (endIndex > array.length) { //若超出范围则循环到数组末端
                    endIndex = array.length;
                }
                for (var i = startIndex; i < endIndex; i++) {
                    tempArray.push(array[i]);
                }
                return tempArray;
            },
            _cacheData: function(jsonArray) {
                var CACHE_ID = 'cube-list-' + this.config['id'];
                if ((this.config.offLine == "true" || this.config.offLine == true) && (this.config.offLinePaging == true || this.config.offLinePaging == 'true')) { //离线缓存翻页

                    if (this.config.isNeedUpdateCache) {
                        //把数组数据存起来
                        Cache.put(CACHE_ID, jsonArray);
                        var ps = parseInt(this.config.pageSize); //pageSize
                        var p = parseInt(this.config.page); //page
                        jsonArray = this._subJSONArray(jsonArray, (p - 1) * ps, (p - 1) * ps + ps);
                        this.config.isNeedUpdateCache = false;
                        this.iScroll.scrollTo(0, 0);
                    }
                } else { //离线模式不该重复存储数据
                    //把数组数据存起来
                    var cache_data = jsonArray;
                    //修改一个bug 当page大于1时才append数据 否则不append
                    if (Cache.get(CACHE_ID) && this.config['page'] > 1) {
                        var olddata = Cache.get(CACHE_ID);
                        cache_data = olddata.concat(jsonArray);
                    }

                    Cache.put(CACHE_ID, cache_data);
                }
                return jsonArray;
            },
            updateCacheInCacheMood: function() {
                if (!this.config.offLine || this.config.offLine == 'false') {
                    throw (Locale.not_offline);
                }
                this.config.isNeedUpdateCache = true;
                this.config.page = 1;
            },

            loadListByJSONArray: function(jsonArray, isLoadFromStore) {
                // console.log('loadListByJSONArray 1: %s', new Date());
                var me = this;
                //加载搜索栏
                me.renderSearchBar();
                if (me.config.page == 1) {
                    me.clearList();
                }

                if (jsonArray === null || jsonArray === undefined || jsonArray.length === 0) {
                    if (me.$(me.config.pageId + ' .cube-list-item-more-record').length === 0) {
                        var li = $("<li/>");
                        li.addClass(me.config.pageId + ' cube-list-item-more-record');
                        li.html(Locale.no_data);
                        li.appendTo(me.el.querySelector(me.config.pageId + ' .contentScroller .item-content'));
                        // $('#pullUp').remove();
                        $("#" + me.config.id).find(me.config.pageId + ' #pullUp').remove();

                        if (me.callback) {
                            me.callback.call();
                        }
                    }
                    return;
                }

                // console.log('loadListByJSONArray 2: %s', new Date());


                //把数组数据存起来
                var cache_data = jsonArray;
                var CACHE_ID = 'cube-list-' + me.config['id'];
                //修改一个bug 当page大于1时才append数据 否则不append
                if (Cache.get(CACHE_ID) && me.config['page'] > 1) {
                    var olddata = Cache.get(CACHE_ID);
                    cache_data = olddata.concat(jsonArray);
                }


                // console.info("list-----config--", me.config);
                if (me.config.offLine == "true" || me.config.offLine == true) {
                    jsonArray = me._cacheData(jsonArray);
                } else {
                    Cache.put(CACHE_ID, cache_data);
                }
                var paging = me.config['paging'];
                var pageSize = parseInt(me.config['pageSize']);
                //加载list如果后台接口没有分页，前台分页
                if ((paging == true || paging == "true") && jsonArray.length > pageSize && me.config.url) {
                    if (me.isLoadNext) {
                        var p = parseInt(this.config.page); //page
                        jsonArray = me._subJSONArray(jsonArray, (p - 1) * pageSize, (p - 1) * pageSize + pageSize);

                    } else {
                        me.config.page = 1;
                        me.clearList();
                        jsonArray = me._subJSONArray(jsonArray, 0, pageSize);
                        me.iScroll.scrollTo(0, 0);
                        me.isLoadNext = true;
                    }


                }
                // console.info("list----jsonArray--", jsonArray);
                //清除store中保存的list数据
                Store.deleteObject(CACHE_ID);

                var skarry;
                var _itemTemplateName = this.config['_itemTemplate'];
                // var paging = this.config['paging'];
                var templateStr;
                if (_itemTemplateName) templateStr = $(this.elContext).find(me.config.pageId + " #" + _itemTemplateName).html();
console.log(templateStr);
                if (me.config['searchkeys']) {

                    skarry = me.config['searchkeys'].split(",");
                }



                // console.log('loadListByJSONArray 3: %s', new Date());

                var fragment = document.createDocumentFragment();
                var item_template = _.template(templateStr);
                for (var i = 0; i < jsonArray.length; i++) {
                    var item = jsonArray[i];

                    /*********************/
                    //add by Simon 20140926
                    var i18nData = me['i18n'];
                    if (i18nData)
                        item.lang = i18nData;
                    /*********************/

                    item.index = i;
                    // item.mainDatas = jsonArray;

                    // item.index = i;
                    var li = $("<li/>");
                    li.addClass('cube-list-item');
                    li.attr('index', (me.config['page'] - 1) * me.config['pageSize'] + i);

                    //为每一个li加上过滤的关键字
                    if (skarry) {
                        var fkword = "";
                        for (var j = 0; j < skarry.length - 1; j++) {
                            if (jsonArray[i][skarry[j]]) {

                                fkword = fkword + jsonArray[i][skarry[j]] + " ";
                            }
                        }

                        if (jsonArray[i][skarry[skarry.length - 1]]) {

                            fkword = fkword + jsonArray[i][skarry[skarry.length - 1]];
                        }
                        li.attr('filter-keyword', fkword.toLowerCase());
                    }

                    //保存列表数据
                    if (isLoadFromStore) {

                    } else {
                        me.StoreListData(item);
                    }
                    if (_itemTemplateName) li.append(item_template(item));
                    //TODO: 需要重构
                    // li.appendTo(me.el.querySelector('.contentScroller .item-content'));
                    fragment.appendChild($(li)[0]);
                }

                // console.log('loadListByJSONArray 4: %s', new Date());
                me.el.querySelector(me.config.pageId + ' .contentScroller .item-content').appendChild(fragment);
                // console.log('loadListByJSONArray 5: %s', new Date());

                //更多按钮
                var moreEl = this.el.querySelector(me.config.pageId + ' .cube-list-item-more');
                if (moreEl) this.$(moreEl).remove();

                //判断页数决定是否显示更多按钮

                if (paging == 'true' && (jsonArray.length % me.config['pageSize']) === 0) {
                    //加上一个加载更多的cell

                    var moreLi = $("<li/>");
                    moreLi.addClass('cube-list-item-more');
                    //TODO: 需要重构
                    moreLi.appendTo(me.el.querySelector(me.config.pageId + ' .contentScroller'));

                    var pullUpText = "<div class='' id='pullUp'><span class='pullUpIcon'></span><span class='pullUpLabel'>" + Locale.pullup_load_more + "</span></div>";
                    var defalutMoreItemDiv = $(pullUpText);
                    moreLi.append(defalutMoreItemDiv);

                } else if (paging !== undefined || (me.totalPage)) {
                    var li = $("<li/>");
                    li.addClass('cube-list-item-more-record');
                    li.html(Locale.no_more_data);
                    // $('#pullUp').remove();
                    //页面中存在多个list时在相应list下查找对象
                    $("#" + me.config.id).find('#pullUp').remove();
                    li.appendTo(me.el.querySelector(me.config.pageId + ' .contentScroller .item-content'));
                }
                me.trigger("drawed", me, jsonArray);
                //me.config.page = me.config.page + 1;
                if (me.config.iScroll != 'false') {
                    $(window).trigger("resize");


                    setTimeout(function() {
                        me.iScroll.refresh();
                    }, 300)

                }

                $(me.config.pageId + " #pullDownRefreshLable").css("display", "none");
                $(me.config.pageId + " #pullDownRefreshLable").css("display", "block");

                // console.log('loadListByJSONArray 6: %s', new Date());
                _winHeight = $(window).height();
                $('.test-lazyload').each(function() {
                    var $self = $(this);
                    if ($self.attr('data-original')) {
                        var _offsetTop = $self.offset().top;
                        //console.log(_offsetTop);
                        if (_offsetTop <= _winHeight + 100 && _offsetTop > -100) {
                            $self.attr('src', $self.attr('data-original'));
                            // $self.removeAttr('data-original');
                            // if (me.config['iRefreshFag'] == 0) {
                            //     me.config['iRefreshFag'] = 1;
                            // }
                        } else {
                            $self.attr('src', '../com.52zzb.common/images/bg_load.png');
                        }
                    }
                });
            },
            getfilterValue: function() {
                var searchBar = document.getElementById(this.config['id'] + '-search');
                if (searchBar) {
                    return $(searchBar).find('input').val();
                }
            },
            renderSearchBar: function() {
                var me = this;
                //加载搜索按钮
                if (me.config['searching'] && me.config['searching'] == 'true') {
                    if (!document.getElementById(me.config['id'] + '-search')) {
                        //加上一个加载更多的cell
                        var searchLi = $("<li/>");

                        searchLi.attr('id', (me.config['id'] + '-search'));

                        var searchInput = $('<input/>');

                        if (me.config.searchText) {
                            searchInput.attr('placeholder', me.config.searchText);
                        } else {
                            searchInput.attr('placeholder', Locale.search);
                        }

                        //css begin
                        searchInput.css('margin-bottom', '0px');
                        searchInput.css('padding-left', '8px');
                        //css end

                        searchInput.attr('type', 'text');
                        //响应键盘弹出来事件touchstart

                        searchInput.bind('touchend input', function(e) {
                            window.scrollTo(0, 0);
                            var inputVal = searchInput.val();
                            me.filterChildren(inputVal);
                        });

                        searchLi.append(searchInput);

                        var navs = document.getElementsByTagName("Nav");
                        var searchNav = navs[navs.length - 1];

                        if (searchNav) {
                            searchNav = $(searchNav);
                            searchLi.css('margin-top', '14px');
                            searchLi.css('padding-top', '5px');
                            searchLi.css('background', '#f6f6f6');
                        } else {

                            searchNav = $("<Nav/>");
                        }
                        searchLi.appendTo(searchNav);

                        searchNav.addClass("bar-standard bar-header-secondary");

                        searchNav.insertBefore($(".content").last());
                    }
                }
            },
            StoreListData: function(item) {
                var CACHE_ID = 'cube-list-' + this.config['id'];
                var tempConfig = this.config;
                tempConfig['el'] = null;
                tempConfig['elContext'] = null;
                tempConfig['elContext'] = null;
                // Store.saveObject(CACHE_ID + "-iscroll", this.iScroll);
                Store.saveObject(CACHE_ID + "-config", tempConfig);
                Store.saveObject(CACHE_ID + "-params", this.requestParams);
                var listStore = [];
                // 把当前list的数据保存起来，方便以后直接拿出来。
                if (Store.loadObject(CACHE_ID) === null) {
                    listStore.push(item);
                    Store.saveObject(CACHE_ID, listStore);
                } else {
                    listStore = Store.loadObject(CACHE_ID);
                    listStore.push(item);
                    Store.saveObject(CACHE_ID, listStore);
                }
            },

            isExistStoreData: function(listName) {
                if (window.localStorage["cube-list-" + listName] === undefined || window.localStorage["cube-list-" + listName] === null) {
                    return false;
                } else {
                    return true;
                }
            },

            loadListByStoreData: function(url, params) {
                console.info("cube-list---list---从store加载数据");
                var CACHE_ID = 'cube-list-' + this.config['id'];
                var listSoreData = Store.loadObject(CACHE_ID);
                var tempConfig = Store.loadObject(CACHE_ID + "-config", tempConfig);
                this.config = _.extend(this.config, tempConfig);
                console.info(this.config);

                if (url) {
                    this.config.url = url;
                }
                var tempparams = Store.loadObject(CACHE_ID + "-params");
                if (params) {
                    params = _.extend(params, tempparams);
                    this.requestParams = _.extend(this.requestParams, params);
                } else {
                    this.requestParams = _.extend(this.requestParams, tempparams);
                }
                console.info(this.requestParams);

                this.loadListByJSONArray(listSoreData, true);

                var scrollY = Store.loadObject(CACHE_ID + "-scrollY");
                // this.iScroll.scrollTo(0, scrollY);
                $(this.iScroll.scroller).css({
                    "-webkit-transform": "translate(0px, " + scrollY + "px)",
                    "transform": "translate(0px, " + scrollY + "px)"
                });
                this.resetPullDownPos(scrollY);
                this.iScroll.refresh();
            },

            cleanStoreListData: function() {
                var CACHE_ID = 'cube-list-' + this.config['id'];
                Store.deleteObject(CACHE_ID);
                Store.deleteObject(CACHE_ID + "-config");
                Store.deleteObject(CACHE_ID + "-params");
                Store.deleteObject(CACHE_ID + "-scrollY");
            },

            clearList: function() {
                var me = this;
                //clear list
                var contentScroller = this.$(me.config.pageId + " .contentScroller");
                var content_holder = contentScroller.find(me.config.pageId + ' .item-content');

                if (this.config['page'] == 1) {
                    content_holder.find("li").remove();
                }
            },

            resetPullDownPos: function(scrollY) {

                if (scrollY < 0) {
                    scrollY = -scrollY;
                }

                if (this.iScroll !== null && this.iScroll !== undefined) {
                    if (scrollY >= 40) {
                        return;
                    }

                    if (this.config.isPullDownRefresh != true) {
                        return;
                    }

                    if (this.iScroll.y <= 40 && this.iScroll.y >= 0) {

                        $(this.iScroll.scroller).css({
                            "-webkit-transform": "translate(0px, " + -40 + "px)",
                            "transform": "translate(0px, " + -40 + "px)"
                        });
                    }
                }
            },

            clearAllList: function() {
                var contentScroller = this.$(me.config.pageId + " .contentScroller");
                var content_holder = contentScroller.find(me.config.pageId + ' .item-content');
                content_holder.find("li").remove();
            },

            loadNextPage: function(callback) {
                var me = this;
                // me.home_refresh();
                if (!me.enableRequest) {
                    return;
                } else {
                    me.enableRequest = false;
                }
                var loader;
                me.requestParams[me.config.pageParam] = this.config['page'];
                me.requestParams['pageSize'] = this.config['pageSize'];
                var _itemTemplateName = this.config['_itemTemplate'];
                if (!me.config['url']) {
                    me.enableRequest = true;
                    return;
                }

                var loderConfig = {
                    autoshow: false,
                    text: Locale.searching
                }
                if (me.config.showloader === true) {
                    loderConfig.autoshow = true;
                } else {
                    loderConfig.autoshow = false;
                }
                if (me.config.loaderText) {
                    loderConfig.text = me.config.loaderText;

                }

                loader = new Loader(loderConfig);

                $.ajax({
                    block: true,
                    timeout: 2000 * 1000,
                    traditional: true,
                    url: me.config['url'],
                    type: me.config['method'],
                    data: me.requestParams,
                    dataType: "json",
                    beforeSend: function(xhr, settings) {
                        if (me.request) {
                            me.request.abort();
                        }
                        me.request = xhr;
                    },
                    complete: function() {
                        me.enableRequest = true;
                        me.request = null;
                        me.refreshIscroll(me);
                        if (callback) {
                            callback();
                        }
                    },
                    success: function(data, textStatus, jqXHR) {

                        me.trigger("load", me, data);
                        me.totalPage = data.totalPage;
                        var i18nData = me['i18n'];
                        // if (data.rows!=undefined&&data.rows !== null && data.rows !== "" && data.rows.length !== 0) {
                        //     $.each(data.rows, function(index, item) {
                        //         item.lang = i18nData;
                        //     // });
                        // }
                        me.isLoadNext = true;
                        var jsonRoot = data;
                        // console.log(jsonRoot);
                        if (me.config.jsonRoot) {
                            _.each(me.config['jsonRoot'].split('.'), function(element) {
                                jsonRoot = jsonRoot[element];
                                element.lang = i18nData;
                            });
                            if (jsonRoot) {
                                for (var i = 0; i < jsonRoot.length; i++) {
                                    //jsonRoot[i]['expath']=pic.expath;
                                    jsonRoot[i]['expath'] = me.config.picserver;
                                    jsonRoot[i]['image100jpg'] = me.config.image100jpg;
                                    jsonRoot[i]['image80jpg'] = me.config.image80jpg;
                                    jsonRoot[i]['imagew300jpg'] = me.config.imagew300jpg;
                                    jsonRoot[i]['imagew200jpg'] = me.config.imagew200jpg;
                                    jsonRoot[i]['imagew600jpg'] = me.config.imagew600jpg;
                                    jsonRoot[i]['imagew600sjpg'] = me.config.imagew600sjpg;

                                    jsonRoot[i]['image120jpg'] = me.config.image120jpg;
                                    jsonRoot[i]['image108jpg'] = me.config.image108jpg;
                                    //jsonRoot[i]['index']=(me.config.page - 1) * me.config.pageSize + i;
                                    jsonRoot[i]['iscroll_num'] = (me.config.page - 1) * me.config.pageSize + i;
                                }
                            }
                        }
                        // console.log(jsonRoot);
                        if (i18nData != undefined && i18nData != null) {
                            $.each(jsonRoot, function(index, item) {
                                item.lang = i18nData;
                            });
                        }
                        //编译模板
                        var templateStr;
                        if (_itemTemplateName) templateStr = this.$("#" + _itemTemplateName).html();
console.log(templateStr);
                        //append
                        var recordsCount = (jsonRoot) ? jsonRoot.length : 0;

                        //在航班动态->中转旅客，如果没有数据会一直卡在loading动画上，因为jsonRoot为null，修改：添加下面这个判断

                        if (jsonRoot) {
                            if (me.config['wrapRefreshDataCallback']) {
                                console.log("list.js>wrapRefreshDataCallback...");
                                jsonRoot = me.config['wrapRefreshDataCallback'](jsonRoot);
                            }
                            me.loadListByJSONArray(jsonRoot);
                        } else {
                            me.trigger("emptyList");
                        }


                        if (me.config['filterStr']) {
                            me.filterChildren(me.config['filterStr']);
                        }
                        //update current number

                        me.trigger("loaded", me, data);

                        //给航班页面中的图片左右滑动 iscroll 初始化开始
                        if (window.location.hash == "#com.52zzb.main/example") {
                            var iNowPage = me.config.page;
                            for (var i = (iNowPage - 1) * 10; i < iNowPage * 10; i++) {
                                if ($('#main-module-example  #img_list_wrap' + i).length) {
                                    new iScroll(me.el.querySelector('#main-module-example #img_list_wrap' + i), {
                                        eventPassthrough: false,
                                        scrollX: true,
                                        scrollY: false,
                                        preventDefault: false
                                    });
                                    //PhotoSwipe.attach(window.document.querySelectorAll('#img_list_wrap' + i + ' a'), options);
                                }
                            }
                        }

                        if (window.location.hash == "#com.52zzb.main/smallshop_me") {
                            var iNowPage1 = me.config.page;
                            for (var i = (iNowPage1 - 1) * 10; i < iNowPage1 * 10; i++) {
                                if ($('#usercenter-module-smallshopMe  #img_list_wrap' + i).length) {
                                    new iScroll(me.el.querySelector('#usercenter-module-smallshopMe #img_list_wrap' + i), {
                                        eventPassthrough: false,
                                        scrollX: true,
                                        scrollY: false,
                                        preventDefault: false
                                    });
                                    //PhotoSwipe.attach(window.document.querySelectorAll('#img_list_wrap' + i + ' a'), options);
                                }
                            }
                        }
                        //图片左右滑动 iscroll 初始化结束

                        loader.hide();
                        me.resetPullDownPos();

                        //Added by Zping on 20140826
                        if (me.config['successCallback'] !== null && me.config['successCallback'] !== undefined) {
                            me.config['successCallback'](me.requestParams);
                        }
                        //End
                    },
                    error: function(e, xhr, type) {
                        me.config.page = me.config.page - 1;
                        loader.hide();
                    }
                });
            }

        }, {
            parseConfig: function(element, attNameList) {

                var jqObject = $(element);

                var config = {};
                for (var i = 0; i < attNameList.length; i++) {
                    var key = attNameList[i];
                    var value = jqObject.attr(key);
                    if (value) config[key] = value;
                }

                return config;
            },

            compile: function(elContext) {
                // console.log('compile');
                var me = this;
                return _.map($(elContext).find("list"), function(tag) {
                    var config = me.parseConfig(tag, ['id', 'itemTemplate', '_itemTemplate', 'moreItemElement', 'url', 'method', 'jsonRoot', 'class', 'paging', 'iScroll', 'isPullDownRefresh', 'autoLoad', 'pageParam', 'searching', 'searchkeys', 'filterStr', 'pageSize', 'skin', 'offLine', 'loaderText', 'searchText', 'width', 'height', 'additionHeight', 'bottomHeight', 'pageId']);

                    //build html
                    //<div id="{id}">
                    //  <div class="contentScroller">
                    //    <div class="item-content">
                    //    </div>
                    //  </div>
                    //</div>
                    var list_el = document.createElement('div');
                    list_el.setAttribute('id', config.id);
                    list_el.setAttribute('data-component', 'list');
                    if (config.skin) {
                        list_el.setAttribute('class', 'cube-list-' + config.skin);
                    } else {
                        list_el.setAttribute('class', 'cube-list-nostyle');
                    }


                    this.$(list_el).css('height', '100%');
                    //整体滚动容器
                    var scroller_el = document.createElement('ul');
                    this.$(scroller_el).addClass('contentScroller');
                    list_el.appendChild(scroller_el);


                    var listContainer = document.createElement('div');
                    if (config.height) {
                        $(listContainer).attr('style', 'height:' + config.height + 'px;');
                    } else {

                        $(listContainer).attr('style', 'height:100%;');
                    }
                    // listContainer.setAttribute('id', 'aaaaaaa');

                    var pullDownRefreshDiv;
                    if (config.isPullDownRefresh == 'true') {
                        //if (true) {
                        //var background-image=
                        pullDownRefreshDiv = document.createElement('div');
                        $(pullDownRefreshDiv).attr('id', 'PullDownRefresh');
                        $(pullDownRefreshDiv).attr('style', 'height: 40px;');
                        // $(pullDownRefreshDiv).attr('style', 'text-align: center;');
                        $(pullDownRefreshDiv).append('<span id="pullDownRefreshIconWarp"><span id="pullDownRefreshIcon"></span></span><span id="pullDownRefreshLable"><div class="spinner"><span>下拉刷新</span><div class="bounce3"></div></div></span>');



                        //$(pullDownRefreshDiv).addClass('pullDownFlip');
                        //$(list_el).prepend(pullDownRefreshDiv);
                        //$(listContainer).appendChild(pullDownRefreshDiv);
                    }



                    //item容器（方便在header和footer之间找到正确位置插入数据行）
                    var content_el = document.createElement('div');
                    this.$(content_el).addClass('item-content');
                    scroller_el.appendChild(content_el);

                    $(list_el).wrap(listContainer);
                    $(list_el).find("div ul").prepend(pullDownRefreshDiv);

                    //replace with html
                    this.$(tag).replaceWith(listContainer);



                    config['el'] = list_el;
                    var pullDownRefreshHeight = parseInt($(pullDownRefreshDiv).css('height'));
                    config['topOffset'] = pullDownRefreshHeight ? pullDownRefreshHeight : 0;
                    config.elContext = elContext;

                    function listSizeFix(arg) {
                        var bodyHeight = $(window).height();
                        var currentTop = $(listContainer).offset().top;
                        var finalHeight = bodyHeight - currentTop;

                        if (config.height) {
                            finalHeight = config.height;
                        }

                        if (config.additionHeight) {
                            finalHeight = finalHeight + parseInt(config.additionHeight);
                        }

                        if (arg && arg.iScroll) {

                            arg.iScroll.wrapperH = finalHeight;
                            arg.iScroll.maxScrollY = -1 * (arg.iScroll.scrollerH - finalHeight - arg.iScroll.y);

                        }
                        // $("#"+config.id).css("height",finalHeight);
                        $('html').css({
                            'min-height': currentTop
                        });

                        if (config.bottomHeight) {
                            finalHeight = finalHeight - config.bottomHeight;
                        }



                        $('body').find(listContainer).css({
                            'height': ((finalHeight) + 'px')
                        });

                        $(config.pageId + '.cube-list-item-more-record').css({
                            'border-bottom': '0px'
                        });

                    }
                    config.listSizeFix = listSizeFix;


                    var list = new List(config);

                    // $(list_el).refresh({ready:function(){}})；
                    Cache.put(config.id + 'Onload', 0);


                    // var timer = setInterval(function() {
                    //     if ($('body').find(listContainer).length > 0) {
                    //         //do something
                    //         listSizeFix();
                    //     }
                    //     var onloadCounter = parseInt(Cache.get(config.id + 'Onload')) + 1;
                    //     if (onloadCounter == 1) {
                    //         $(window).on('resize', listSizeFix);
                    //         $(listContainer).unload(function() {
                    //             $(window).off('resize', listSizeFix);
                    //         });

                    //     }
                    //     if (onloadCounter > 1 && $('body').find(listContainer).length == 0) {
                    //         clearInterval(timer);
                    //     } else {
                    //         Cache.put(config.id + 'Onload', onloadCounter);
                    //     }
                    // }, 500);


                    return list;
                });
            }
        });

        return List;
    });
